<template>
  <el-dialog v-model="visible" title="用户登录" width="400px" :show-close="false">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>{{ isLogin ? '登录' : '注册' }}</span>
        <el-button @click="toggleMode" type="text" style="float: right; padding: 3px 0; color: var(--el-color-primary)">
          {{ isLogin ? '注册新账号' : '已有账号？登录' }}
        </el-button>
      </div>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="账号密码登录" name="account"></el-tab-pane>
        <el-tab-pane label="手机号登录" name="phone"></el-tab-pane>
        <el-tab-pane label="邮箱登录" name="email"></el-tab-pane>
      </el-tabs>

      <el-form ref="form" :model="formData" :rules="rules" label-width="0px">
        <el-form-item v-if="activeTab === 'account'" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号" clearable>
            <template #prefix>
              <i class="el-icon-user"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-else :prop="activeTab === 'phone' ? 'phone' : 'email'">
          <el-input v-model="formData[activeTab === 'phone' ? 'phone' : 'email']"
            :placeholder="activeTab === 'phone' ? '请输入手机号' : '请输入邮箱地址'"
            clearable>
            <template #prefix>
              <i class="el-icon-message"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="formData.password" type="password" show-password placeholder="请输入密码"
            clearable>
            <template #prefix>
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="!isLogin" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" type="password" show-password placeholder="请确认密码"
            clearable>
            <template #prefix>
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-button type="primary" @click="submitForm" style="width: 100%">{{
          isLogin ? '登录' : '注册'
          }}</el-button>
      </el-form>
    </el-card>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useProfileStore } from '@/store/profile'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

interface FormData {
  username: string
  phone: string
  email: string
  password: string
  confirmPassword: string
}


const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = ref<FormInstance>()
const activeTab = ref<string>('phone')
const isLogin = ref<boolean>(true)

const formData = reactive<FormData>({
  username: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
})

const validatePassword = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!isLogin.value && value !== formData.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules: FormRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '邮箱格式不正确',
      trigger: 'blur',
    },
  ],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: validatePassword, trigger: 'blur' }],
}

const toggleMode = () => {
  isLogin.value = !isLogin.value
}

const handleTabChange = (tab: string) => {
  // 清空当前激活的输入框内容
  if (tab === 'phone') {
    formData.email = ''
  } else {
    formData.phone = ''
  }

  // 重置表单验证状态
  form.value?.clearValidate()
  console.log('当前选中标签:', tab)
}

const profileStore = useProfileStore()

const router = useRouter()
const submitForm = async () => {
  if (!form.value) return
  try {
    const valid = await form.value.validate()
    if (valid) {
      if (isLogin.value) {
        console.log('提交登录:', formData)
        let account = ''
        if (activeTab.value === 'account') {
          account = formData.username
        } else {
          account = activeTab.value === 'phone' ? formData.phone : formData.email
        }
        
        // 调用真实的登录接口
        try {
          await profileStore.login(account, formData.password)
          visible.value = false
          router.push('/profile') // 登录成功后跳转到个人中心
          ElMessage.success('登录成功')
        } catch (error) {
          ElMessage.error('登录失败')
        }
      } else {
        console.log('提交注册:', formData)
        // 处理注册逻辑
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.box-card {
  border: none;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>